﻿#include "as_signal.h"

#ifdef _WIN32
#include <windows.h>
//windows下ctrl + c 是用这个宏
//#define SIGINT CTRL_C_EVENT

//void sys_signal(int signum, PHANDLER_ROUTINE fun)
//{ 
//    SetConsoleCtrlHandler(fun, true);
//}

#else
#include <signal.h>
//typedef signal sys_signal;
#endif

using namespace as::tools;
std::map<int, std::function<void()> > Signal::handlers;
#ifdef _WIN32
bool __stdcall Signal::signal_handler(int signal)
{
	auto it = Signal::handlers.find(signal);
	if (it != Signal::handlers.end())
	{
		it->second();
		return true;
	}

	return false;
}
#else
void Signal::signal_handler(int signal)
{
	auto it = handlers.find(signal);
	if (it != handlers.end())
	{
		it->second();
	}
}


#endif

void Signal::register_signal(int signum, std::function<void()> &&func)
{
	handlers[signum] = func;
#ifdef _WIN32
	signal(signum, (_crt_signal_t)Signal::signal_handler);
#else
	signal(signum, [](int signal){Signal::signal_handler(signal);});
#endif
}
